package com.obixlabs.security.credentialsstore.server.serviceimpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.obixlabs.security.credentialsstore.exception.EntryNotFoundException;
import com.obixlabs.security.credentialsstore.model.ObixGroups;
import com.obixlabs.security.credentialsstore.model.ObixPermission;
import com.obixlabs.security.credentialsstore.model.ObixPermissions;
import com.obixlabs.security.credentialsstore.server.dao.GroupDAO;
import com.obixlabs.security.credentialsstore.server.dao.PermissionDAO;
import com.obixlabs.security.credentialsstore.services.PermissionsManagementService;

public class PermissionsManagementServiceDefaultImpl 	extends ConcurrentServiceBase 
														implements PermissionsManagementService
{	
	private static final Logger logger = 
		LoggerFactory.getLogger(PermissionsManagementServiceDefaultImpl.class);
	
	private PermissionDAO permissionDAO;
	private GroupDAO groupDAO;
	
	public PermissionDAO getPermissionDAO(){return permissionDAO;}
	public void setPermissionDAO(PermissionDAO permissionDAO)
	{this.permissionDAO = permissionDAO;}	
	
	public GroupDAO getGroupDAO() {return groupDAO;}
	public void setGroupDAO(GroupDAO groupDAO)
	{this.groupDAO = groupDAO;}
	
	public ObixPermissions getAllPermissions()
	{
		lockForRead();
		try{		
			return permissionDAO.findAll();
		} finally {unlockAfterRead();}			
	}
		
	@Override
	public ObixPermission getPermission(String name)
	{
		lockForRead();
		try
		{
			ObixPermission result = permissionDAO.findByName(name);
			if (logger.isDebugEnabled())
				logger.debug("Search by name '"+name+"' returned '" + result + "'.");
			return result;
		}
		finally {unlockAfterRead();}
	}
	
	@Override
	public ObixGroups getGroupsAssignedTo(ObixPermission permission) 
											throws EntryNotFoundException
	{
		lockForRead();
		try
		{		
			ObixGroups result = groupDAO.findByPermission(permission);
			if (logger.isDebugEnabled())
				logger.debug("Search by '"+permission +"' returned " + result.size() + " entries");
			return result;
		}
		finally {unlockAfterRead();}			
	}
			
	@Override
	public void savePermission(ObixPermission permission)
	{
		lockForWrite();
		try
		{				
			if (logger.isDebugEnabled())
				logger.debug("Saving '"+permission +"'.");
			permissionDAO.save(permission);
		}
		finally {unlockAfterWrite();}						
	}
	
	@Override
	public void deletePermission(ObixPermission permission)
	{
		lockForWrite();
		try
		{						
			if (logger.isDebugEnabled())
				logger.debug("Deleting '"+permission +"'.");
			permissionDAO.delete(permission);
		}
		finally {unlockAfterWrite();}			
	}
	
	public String getServiceName(){return PermissionsManagementService.SERVICE_NAME;}
	
}//end class def